﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using Mortgage.DAL.Entity;
using Mortgage.UserControl;

namespace Mortgage.Form
{
    public partial class Agent : System.Web.UI.Page
    {
        Mortgage.Srv.IAgentSrv svc = Mortgage.Srv.SrvFactory.CreateAgentSrv();

        #region event handler
        protected void Page_Load(object sender, EventArgs e)
        {
            this.grdAgent.RowDataBound += new GridViewRowEventHandler(grdAgent_RowDataBound);
            if (!this.Page.IsPostBack)
            {
                grdAgent.PageIndex = 1;
                BindGridView();

                FormMode = EnmFormMode.Blank;
                HandleFormState(FormMode);
            }

        }

        void grdAgent_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdAgent, "Select$" + e.Row.RowIndex);
            }
        }





        protected void grdAgent_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(grdAgent.DataKeys[grdAgent.SelectedIndex].Value.ToString());
            tAgent usr = svc.GetById(id);
            if (usr == null)
                Entity = new tAgent();
            else
                Entity = usr;

            // Update mode
            FormMode = EnmFormMode.Edit;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            // Update mode
            Entity = new tAgent() { };
            FormMode = EnmFormMode.Insert;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            BindEntity();
            // clear error Message
            DialogMess.Text = string.Empty;
            DialogMess.CssClass = "successBox";
            if (FormMode == EnmFormMode.Insert) // Insert Mode
            {

                try
                {
                    if (svc.Insert(Entity) == 0)
                    {
                        DialogMess.Text = "Cập nhật thành công!";
                        BindGridView();

                        // Translate to update mode
                        // Update mode
                        FormMode = EnmFormMode.Edit;
                        HandleFormState(FormMode);
                        BindView();
                    }
                }
                catch (Exception ex)
                {
                    DialogMess.Text = ex.Message;
                    DialogMess.CssClass = "failureBox";
                }


            }
            else
            {

                if (svc.Update(Entity) == 0)
                {

                    DialogMess.Text = "Cập nhật thành công!";
                    BindGridView();

                    // Translate to update mode
                    // Update mode
                    FormMode = EnmFormMode.Edit;
                    HandleFormState(FormMode);
                    BindView();
                }


            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            BindEntity();
            svc.Delete(Entity);
            BindGridView();
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }



        #endregion

        #region Function

        protected void BindAgentOnMaster()
        {
            Mortgage.SiteMaster master = this.Master as Mortgage.SiteMaster;
            if (master != null)
                master.BindAgents();
        }

        protected void BindGridView()
        {
            grdAgent.DataSource = svc.GetAll();
            grdAgent.DataBind();

            BindAgentOnMaster();
        }

        #endregion


        #region Property

        public tAgent Entity
        {
            get;
            set;
        }

        public EnmFormMode FormMode
        {
            get
            {
                if (ViewState["_ViewState"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewState"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewState"] = value;
            }
        }

        #endregion

        #region Binding

        protected void HandleFormState(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;


                    BlankControl();
                    EnableControl(false);
                    Entity = new tAgent();

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = !(svc.GetAll().Count <= 1);
                    if (btnDelete.Enabled)
                        btnDelete.Enabled = svc.CanDelete(Entity);
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    EnableControl(true);

                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;

                    EnableControl(true);

                    break;
            }

            BindView();
        }

        protected void EnableControl(bool enable)
        {

            fldName.Enabled = enable;
            fldAddress.Enabled = enable;
            fldTelephone.Enabled = enable;
            fldDescription.Enabled = enable;

        }

        protected void BindView()
        {
            fldName.Text = Entity.Name;
            fldAddress.Text = Entity.Address;
            fldTelephone.Text = Entity.Telephone;
            fldDescription.Text = Entity.Description;
            fldID.Value = Entity.ID.ToString();
        }

        protected void BindEntity()
        {
            tAgent entity = new tAgent();
            if (Entity != null)
                entity.ID = Entity.ID;

            entity.ID = Convert.ToInt32(fldID.Value);
            entity.Name = fldName.Text;
            entity.Address = fldAddress.Text.Trim();
            entity.Telephone = fldTelephone.Text.Trim();
            entity.Description = fldDescription.Text.Trim();



            Entity = entity;
            BindProperty();
        }

        protected void BlankControl()
        {
            fldName.Text = string.Empty;
            fldAddress.Text = string.Empty;
            fldTelephone.Text = string.Empty;
            fldDescription.Text = string.Empty;

            DialogMess.CssClass = string.Empty;
            DialogMess.Text = string.Empty;

        }


        protected void BindProperty()
        {
            MembershipUser membershipUser = System.Web.Security.Membership.GetUser();
            if (membershipUser != null)
            {
                Entity.CreatedBy = membershipUser.UserName;
                Entity.ModifiedBy = membershipUser.UserName;
                Entity.CreatedDate = DateTime.Now;
                Entity.ModifiedDate = DateTime.Now;

            }

        }

        #endregion
    }
}